package lion.blog.execution.admin;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import lion.blog.model.BlogArticle;
import lion.blog.model.BlogCatelog;
import lion.blog.model.BlogComment;
import lion.blog.model.BlogMenu;
import lion.blog.model.BlogSetting;
import lion.blog.model.BlogSource;
import lion.blog.model.BlogTag;
import lion.blog.model.FLinks;
import lion.blog.util.BlogUtil;
import lion.dev.lang.KV;
import lion.dev.lang.MapJ;
import lion.dev.net.IP;
import lion.dev.net.IPBase;
import lion.dev.web.Validator;
import lion.dev.web.paging.PagedVo;
import lion.framework.core.bean.anno.Inject;
import lion.framework.core.db.DB;
import lion.framework.core.db.DataTable;
import lion.framework.core.db.SessionFactory;
import lion.framework.core.db.paging.SQLPagingFactory;
import lion.framework.core.util.AppPaths;
import lion.framework.core.web.anno.Namespace;
import lion.framework.core.web.anno.Path;
import lion.framework.core.web.anno.Result;
import lion.framework.core.web.anno.View;
import lion.framework.core.web.exception.WebException;
import lion.framework.core.web.request.Request;
import lion.framework.core.web.views.ResultType;
import lion.web.platform.PlatformModule;
import lion.web.platform.model.User;
import lion.web.platform.priv.user.LoginUser;
import lion.web.platform.system.prop.PropService;
import lion.web.platform.system.prop.model.ModelProp;

/**
 * @author lion
 * @email hl_0074@sina.com
 * @date 2015年8月27日
 */
@Namespace("/#{admin}/blog")
public class BlogAdminExecution {

	@Inject("platform.PropService")
	private PropService service;

	@Path("article")
	@Result(@View("/WEB-INF/template/blog/article/index.jsp"))
	public String index(Request request) {

		return "success";
	}

	@Path("article/edit")
	@Result(@View("/WEB-INF/template/blog/article/edit.jsp"))
	public String editArticle(Request request) {

		int id = request.getInt("id");
		if (id > 0) {

			BlogArticle article = BlogArticle.load(id);
			MapJ param = article.valueMap();

			for (ModelProp mp : service.getModelProps("article", id)) {
				param.put(mp.getProp(), mp.getValue());
			}
			request.addModel("article", param);
		}

		return "success";
	}

	@Path("article/delete")
	@Result(@View("/WEB-INF/template/blog/article/edit.jsp"))
	public String deleteArticle(Request request) {

		int[] ids = Validator.toIntArray(request.getString("ids"));
		if (ids.length > 0) {
			BlogArticle.delete(ids);
		}

		// delete the props
		for (int id : ids) {
			service.deleteModelProp("article", id);
		}
		// update the catelog num
		// SessionFactory.getCurrentDB().update("update BlogCatelog set
		// num=num-1 where num>0 and id in(" + Lang.join(ids) + ")");
		return "success";
	}

	@Path("article/save")
	@Result(@View(type = ResultType.JSON))
	public String saveArticle(Request request) {

		BlogArticle blog = BlogArticle.create(request);
		blog.setCreateTime(new Date());
		blog.setCreator(LoginUser.current().getUser().getId());

		if (blog.getPublishTime() == null && !blog.isDraft()) {
			blog.setPublishTime(new Date());
		}

		if (StringUtils.isBlank(blog.getAuthor())) {
			blog.setAuthor(LoginUser.current().getUser().getRealName());
		}

		blog.save();
		// source
		DB db = SessionFactory.getCurrentDB();
		if (StringUtils.isNotBlank(blog.getSource())) {
			BlogSource source = BlogSource.load("where name=:source", request, db);
			if (source == null) {
				source = new BlogSource();
				source.setName(blog.getSource());
				source.save();
			}
		}

		// tags
		if (StringUtils.isNotBlank(blog.getTags())) {
			for (String tag : StringUtils.split(blog.getTags(), ",")) {

				if (!db.queryTrue("select 1 from BlogTag where name=?", tag)) {
					BlogTag blogTag = new BlogTag();
					blogTag.setName(tag);
					blogTag.save();
				}
			}
		}

		service.saveModelProps("article", blog.getId(), request);

		// 草稿
		// 发布

		// SessionFactory.getCurrentDB().update("update BlogCatelog set
		// num=num+1 where id=?", blog.getCatelog());

		request.addModel("id", blog.getId());

		return "success";
	}

	@Path("article/update")
	@Result(@View(type = ResultType.JSON))
	public String updateArticle(Request request) {

		BlogArticle blog = BlogArticle.create(request);

		BlogArticle old = BlogArticle.load(blog.getId());
		if (old == null) {
			request.addError("msg", "博客未找到");
			return "success";
		}
		blog.setCreateTime(old.getCreateTime());
		blog.setCreator(old.getCreator());

		// 如果为空，作者为创建者
		if (StringUtils.isBlank(blog.getAuthor())) {
			User user = User.load(blog.getCreator());
			if (user != null) {
				blog.setAuthor(user.getRealName());
			}
		}

		blog.update();

		// source
		DB db = SessionFactory.getCurrentDB();
		if (StringUtils.isNotBlank(blog.getSource())) {
			BlogSource source = BlogSource.load("where name=:source", request, db);
			if (source == null) {
				source = new BlogSource();
				source.setName(blog.getSource());
				source.save();
			}
		}

		// tags
		if (StringUtils.isNotBlank(blog.getTags())) {
			for (String tag : StringUtils.split(blog.getTags(), ",")) {

				if (!db.queryTrue("select 1 from BlogTag where name=?", tag)) {
					BlogTag blogTag = new BlogTag();
					blogTag.setName(tag);
					blogTag.save();
				}
			}
		}

		// save blog props
		service.saveModelProps("article", blog.getId(), request);

		// update blog catelog articlue num
		// if (catelog != old.getCatelog()) {
		// SessionFactory.getCurrentDB().update("update BlogCatelog set
		// num=num+1 where id=?", catelog);
		// SessionFactory.getCurrentDB().update("update BlogCatelog set
		// num=num-1 where id=? and num>0", old.getCatelog());
		// }

		request.addModel("id", blog.getId());
		return "success";
	}

	@Path("article/publish")
	@Result(@View(type = ResultType.JSON))
	public String publishArticle(Request request) {

		int id = request.getInt("id");
		if (id > 0) {
			SessionFactory.getCurrentDB().update(BlogArticle.TABLE_NAME, new KV<String, Integer>("id", id), new KV<String, Boolean>("draft", false),
					new KV<String, Date>("publishTime", new Date()));
		}

		try {
			PlatformModule.eventManager.fire("blog.article.published", id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	@Path("article/preview")
	@Result({ @View(name = "success", value = "/WEB-INF/blog/theme/{theme}/{page}") })
	public String previewArticle(Request request) {

		int id = request.getInt("id");

		BlogArticle article = BlogArticle.load(id);
		if (article == null) { throw new WebException(404, "Article Not Found"); }

		MapJ param = article.valueMap();
		param.put("url", BlogUtil.getBlogLink(param, null));
		param.put("catelog", null);
		request.addModel("article", param);

		request.addModel("theme", BlogUtil.getCurrentTheme());
		String page = "detail.jsp";
		if (StringUtils.isNotBlank(article.getTemplate())) {
			page = article.getTemplate();
		}
		request.addModel("page", page);
		return "success";

	}

	@Path("article/list")
	@Result(@View(type = ResultType.JSON))
	public String listArticle(Request request) {

		int page = request.getInt("page", 1);
		int size = request.getInt("size", 20);

		int catelog = request.getInt("catelog");
		PagedVo<MapJ> pagedVo = null;
		if (catelog > 0) {
			pagedVo = new PagedVo<>(BlogArticle.count("where catelog=:catelog", request));
		} else {
			pagedVo = new PagedVo<>(BlogArticle.count());
		}
		pagedVo.getPaging().setPageNumber(page);
		pagedVo.getPaging().setPageSize(size);

		String sql = null;
		if (catelog > 0) {
			sql = "select ba.*,(select name from BlogCatelog bc where bc.id=ba.catelog) catelogName,(select name from User u where u.id=ba.creator ) creatorName from BlogArticle ba where ba.catelog=:catelog order by ba.id desc";
		} else {
			sql = "select ba.*,(select name from BlogCatelog bc where bc.id=ba.catelog) catelogName,(select name from User u where u.id=ba.creator ) creatorName from BlogArticle ba order by ba.id desc";
		}

		DB db = SessionFactory.getCurrentDB();
		DataTable table = db.query(SQLPagingFactory.paging(db.getType(), sql, pagedVo.getPaging().getStartRowNumber(), pagedVo.getPaging().getPageSize()), request);
		pagedVo.setVos(table.getRows());

		request.addModel("json", pagedVo);
		return "success";
	}

	// comment

	@Path("comment")
	@Result(@View("/WEB-INF/template/blog/comment/index.jsp"))
	public String comment(Request request) {

		return "success";
	}

	@Path("comment/list")
	@Result(@View(type = ResultType.JSON))
	public String listComment(Request request) {

		int articleId = request.getInt("articleId");
		int page = request.getInt("page", 1);
		int size = request.getInt("size", 20);

		PagedVo<MapJ> pagedVo = null;
		if (articleId > 0) {
			pagedVo = new PagedVo<>(BlogComment.count("where article=:articleId", request));
		} else {
			pagedVo = new PagedVo<>(BlogComment.count());
		}

		pagedVo.getPaging().setPageNumber(page);
		pagedVo.getPaging().setPageSize(size);

		String sql = "select bc.*,ba.id,ba.title from BlogComment bc,BlogArticle ba where bc.article=ba.id";
		if (articleId > 0) {
			sql += " and bc.article=:articleId";
		}

		sql += " order by bc.id desc";

		DB db = SessionFactory.getCurrentDB();
		List<MapJ> rows = db.query(SQLPagingFactory.paging(db.getType(), sql, pagedVo.getPaging().getStartRowNumber(), pagedVo.getPaging().getPageSize()), request).getRows();

		for (MapJ row : rows) {
			String sip = row.getString("ip");
			if (StringUtils.isNotBlank(sip)) {
				IP ip = IPBase.query(sip);
				row.put("addr", ip.getArea() + "(" + ip.getPosition() + ")");
			}
		}
		pagedVo.setVos(rows);

		request.addModel("json", pagedVo);

		return "success";
	}

	// catelog
	@Path("catelog")
	@Result(@View("/WEB-INF/template/blog/catelog/index.jsp"))
	public String catelog(Request request) {

		return "success";
	}

	@Path("catelog/list")
	@Result(@View(type = ResultType.JSON))
	public String listCatelog(Request request) {

		request.addModel("data", BlogCatelog.list(-1));

		return "success";
	}

	@Path("catelog/save")
	@Result(@View(type = ResultType.JSON))
	public String saveCatelog(Request request) {

		BlogCatelog catelog = BlogCatelog.create(request);
		if (StringUtils.isBlank(catelog.getName()) || StringUtils.isBlank(catelog.getCode())) {
			request.addError("msg", "name 或 code 不能为空");
			return "success";
		}
		if (BlogCatelog.load("where code=:code or name=:name", request, SessionFactory.getCurrentDB()) != null) {
			request.addError("msg", "分类目录名称或code已存在,请更换");
			return "success";
		}

		catelog.save();

		return "success";
	}

	@Path("catelog/update")
	@Result(@View(type = ResultType.JSON))
	public String updateCatelog(Request request) {

		// 名称查询
		BlogCatelog catelog = BlogCatelog.create(request);
		if (StringUtils.isBlank(catelog.getName()) || StringUtils.isBlank(catelog.getCode())) {
			request.addError("msg", "name 或 code 不能为空");
			return "success";
		}
		if (BlogCatelog.load("where id<>:id and (code=:code or name=:name)", request, SessionFactory.getCurrentDB()) != null) {
			request.addError("msg", "分类目录名称或code已存在,请更换");
			return "success";
		}
		catelog.update();

		return "success";
	}

	@Path("catelog/delete")
	@Result(@View(type = ResultType.JSON))
	public String deleteCatelog(Request request) {

		int id = request.getInt("id");
		if (id > 0) {
			BlogCatelog catelog = BlogCatelog.load(id);
			if (catelog == null) { throw new WebException("分类不存在"); }
			if (catelog.getNum() > 0) { throw new WebException("分类中有文档"); }
			catelog.delete();
		}
		return "success";
	}

	@Path("catelog/edit")
	@Result(@View("/WEB-INF/template/blog/catelog/edit.jsp"))
	public String editCatelog(Request request) {

		int id = request.getInt("id");
		if (id > 0) {
			request.addModel("catelog", BlogCatelog.load(id));
		}

		return "success";
	}

	// menu
	@Path("menu")
	@Result(@View("/WEB-INF/template/blog/menu/index.jsp"))
	public String menu(Request request) {

		return "success";
	}

	@Path("menu/list")
	@Result(@View(type = ResultType.JSON))
	public String listMenu(Request request) {

		List<BlogMenu> menus = BlogMenu.list(-1, " order by sid,id");

		request.addModel("vos", menus);

		return "success";
	}

	@Path("menu/save")
	@Result(@View(type = ResultType.JSON))
	public String saveMenu(Request request) {

		BlogMenu menu = BlogMenu.create(request);

		if (StringUtils.isBlank(menu.getName()) || StringUtils.isBlank(menu.getUrl())) {
			request.addError("msg", "数据不完整");
			return "success";
		}

		if (menu.getSid() < 0) {
			menu.setSid(0);
		}

		menu.save();

		return "success";
	}

	@Path("menu/update")
	@Result(@View(type = ResultType.JSON))
	public String updateMenu(Request request) {

		BlogMenu menu = BlogMenu.create(request);

		if (StringUtils.isBlank(menu.getName()) || StringUtils.isBlank(menu.getUrl())) {
			request.addError("msg", "数据不完整");
			return "success";
		}
		if (menu.getSid() < 0) {
			menu.setSid(0);
		}
		menu.update();

		return "success";
	}

	@Path("menu/delete")
	@Result(@View(type = ResultType.JSON))
	public String deleteMenu(Request request) {

		int[] ids = Validator.toIntArray(request.getString("ids"));
		BlogMenu.delete(ids);

		return "success";
	}

	@Path("menu/edit")
	@Result(@View("/WEB-INF/template/blog/menu/edit.jsp"))
	public String editMenu(Request request) {

		int id = request.getInt("id");
		if (id > 0) {
			request.addModel("menu", BlogMenu.load(id));
		}

		return "success";
	}

	// source
	@Path("source")
	@Result(@View("/WEB-INF/template/blog/source/index.jsp"))
	public String source(Request request) {

		return "success";
	}

	@Path("source/chooser")
	@Result(@View("/WEB-INF/template/blog/source/chooser.jsp"))
	public String chooseSource(Request request) {

		return "success";
	}

	@Path("source/list")
	@Result(@View(type = ResultType.JSON))
	public String listSource(Request request) {

		int page = request.getInt("page", 1);
		int size = request.getInt("size", 30);

		PagedVo<BlogSource> pagedVo = new PagedVo<>(BlogSource.count());
		pagedVo.getPaging().setPageNumber(page);
		pagedVo.getPaging().setPageSize(size);

		pagedVo.setVos(BlogSource.list(pagedVo.getPaging().getStartRowNumber(), pagedVo.getPaging().getPageSize()));

		request.addModel("json", pagedVo);

		return "success";
	}

	@Path("source/update")
	@Result(@View(type = ResultType.JSON))
	public String updateSource(Request request) {

		if (StringUtils.isNotBlank(request.getString("name"))) {
			SessionFactory.getCurrentDB().update(BlogSource.TABLE_NAME, new KV<String, Integer>("id", request.getInt("id")),
					new KV<String, String>("name", request.getString("name")));
		}

		return "success";
	}

	@Path("source/delete")
	@Result(@View(type = ResultType.JSON))
	public String deleteSource(Request request) {

		int ids[] = Validator.toIntArray(request.getString("ids"));
		if (ids.length > 0) {
			BlogSource.delete(ids);
		}

		return "success";
	}

	@Path("source/save")
	@Result(@View(type = ResultType.JSON))
	public String saveSource(Request request) {

		BlogSource source = BlogSource.create(request);
		if (StringUtils.isBlank(source.getName())) {
			request.addError("msg", "名称不能为空");
			return "success";
		}
		source.save();
		return "success";
	}

	// tags
	@Path("tags")
	@Result(@View("/WEB-INF/template/blog/tag/index.jsp"))
	public String tags(Request request) {

		return "success";
	}

	@Path("tag/chooser")
	@Result(@View("/WEB-INF/template/blog/tag/chooser.jsp"))
	public String chooseTag(Request request) {

		return "success";
	}

	@Path("tag/list")
	@Result(@View(type = ResultType.JSON))
	public String listTag(Request request) {

		int page = request.getInt("page", 1);
		int size = request.getInt("size", 30);

		PagedVo<BlogTag> pagedVo = new PagedVo<>(BlogTag.count());
		pagedVo.getPaging().setPageNumber(page);
		pagedVo.getPaging().setPageSize(size);

		pagedVo.setVos(BlogTag.list(pagedVo.getPaging().getStartRowNumber(), pagedVo.getPaging().getPageSize()));

		request.addModel("json", pagedVo);

		return "success";
	}

	@Path("tag/update")
	@Result(@View(type = ResultType.JSON))
	public String updateTag(Request request) {

		if (StringUtils.isNotBlank(request.getString("name"))) {
			SessionFactory.getCurrentDB().update(BlogTag.TABLE_NAME, new KV<String, Integer>("id", request.getInt("id")),
					new KV<String, String>("name", request.getString("name")));
		}

		return "success";
	}

	@Path("tag/delete")
	@Result(@View(type = ResultType.JSON))
	public String deleteTag(Request request) {

		int ids[] = Validator.toIntArray(request.getString("ids"));
		if (ids.length > 0) {
			BlogTag.delete(ids);
		}

		return "success";
	}

	@Path("tag/save")
	@Result(@View(type = ResultType.JSON))
	public String saveTag(Request request) {

		BlogTag tag = BlogTag.create(request);
		if (StringUtils.isBlank(tag.getName())) {
			request.addError("msg", "名称不能为空");
			return "success";
		}
		tag.save();
		return "success";
	}

	// setting

	@Path("setting")
	@Result(@View("/WEB-INF/template/blog/setting/index.jsp"))
	public String setting(Request request) {

		return "success";
	}

	@Path("setting/edit")
	@Result(@View("/WEB-INF/template/blog/setting/edit.jsp"))
	public String editSetting(Request request) {

		int id = request.getInt("id");
		if (id > 0) {
			request.addModel("setting", BlogSetting.load(id));
		}
		return "success";
	}

	@Path("setting/list")
	@Result(@View(type = ResultType.JSON))
	public String listSetting(Request request) {

		int page = request.getInt("page", 1);
		int size = request.getInt("size", 30);

		PagedVo<BlogSetting> pagedVo = new PagedVo<>(BlogSetting.count());
		pagedVo.getPaging().setPageNumber(page);
		pagedVo.getPaging().setPageSize(size);

		pagedVo.setVos(BlogSetting.list(pagedVo.getPaging().getStartRowNumber(), pagedVo.getPaging().getPageSize()));

		request.addModel("json", pagedVo);
		return "success";
	}

	@Path("setting/save")
	@Result(@View(type = ResultType.JSON))
	public String saveSetting(Request request) {

		BlogSetting setting = BlogSetting.create(request);
		if (StringUtils.isBlank(setting.getName()) || StringUtils.isBlank(setting.getCode())) {
			request.addError("msg", "name 或 code 不能为空");
			return "success";
		}
		if (BlogSetting.load("where code=:code ", request, SessionFactory.getCurrentDB()) != null) {
			request.addError("msg", "相同code已存在,请更换");
			return "success";
		}
		setting.save();
		try {
			PlatformModule.eventManager.fire("blog.setting:change");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	@Path("setting/update")
	@Result(@View(type = ResultType.JSON))
	public String updateSetting(Request request) throws Exception {

		BlogSetting setting = BlogSetting.create(request);
		if (StringUtils.isBlank(setting.getName()) || StringUtils.isBlank(setting.getCode())) {
			request.addError("msg", "name 或 code 不能为空");
			return "success";
		}
		if (BlogSetting.load("where id<>:id and code=:code ", request, SessionFactory.getCurrentDB()) != null) {
			request.addError("msg", "相同key已存在,请更换");
			return "success";
		}
		setting.update();

		PlatformModule.eventManager.fire("blog.setting:change", SessionFactory.getCurrentDB());

		return "success";
	}

	@Path("setting/delete")
	@Result(@View(type = ResultType.JSON))
	public String deleteSetting(Request request) {

		int[] ids = Validator.toIntArray(request.getString("ids"));
		if (ids.length > 0) {
			BlogSetting.delete(ids);
		}

		try {
			PlatformModule.eventManager.fire("blog.setting:change");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	// frlinks
	@Path("frlinks")
	@Result(@View("/WEB-INF/template/blog/frlinks/index.jsp"))
	public String frlinks(Request request) {

		return "success";
	}

	@Path("frlinks/edit")
	@Result(@View("/WEB-INF/template/blog/frlinks/edit.jsp"))
	public String editFrlinks(Request request) {

		int id = request.getInt("id");
		if (id > 0) {
			request.addModel("link", FLinks.load(id));
		}
		return "success";
	}

	@Path("frlinks/list")
	@Result(@View(type = ResultType.JSON))
	public String listFrlinks(Request request) {

		int page = request.getInt("page", 1);
		int size = request.getInt("size", 30);

		PagedVo<FLinks> pagedVo = new PagedVo<>(FLinks.count());
		pagedVo.getPaging().setPageNumber(page);
		pagedVo.getPaging().setPageSize(size);

		pagedVo.setVos(FLinks.list(pagedVo.getPaging().getStartRowNumber(), pagedVo.getPaging().getPageSize()));

		request.addModel("json", pagedVo);
		return "success";
	}

	@Path("frlinks/save")
	@Result(@View(type = ResultType.JSON))
	public String saveFrlinks(Request request) {

		FLinks fLinks = FLinks.create(request);
		if (StringUtils.isBlank(fLinks.getName())) {
			request.addError("msg", "链接名称不能为空");
			return "success";
		}
		fLinks.save();
		return "success";
	}

	@Path("frlinks/update")
	@Result(@View(type = ResultType.JSON))
	public String updateFrlinks(Request request) {

		FLinks fLinks = FLinks.create(request);
		if (StringUtils.isBlank(fLinks.getName())) {
			request.addError("msg", "链接名称不能为空");
			return "success";
		}
		fLinks.update();
		return "success";
	}

	@Path("frlinks/delete")
	@Result(@View(type = ResultType.JSON))
	public String deleteFrlinks(Request request) {

		int[] ids = Validator.toIntArray(request.getString("ids"));
		if (ids.length > 0) {
			FLinks.delete(ids);
		}
		return "success";
	}

	// archives
	@Path("archive")
	@Result(@View("/WEB-INF/template/blog/archive/index.jsp"))
	public String archive(Request request) {

		return "success";
	}

	// themes
	@Path("theme")
	@Result(@View("/WEB-INF/template/blog/theme/index.jsp"))
	public String theme(Request request) {

		// 显示页面
		BlogSetting blogSetting = BlogSetting.load("where code='theme'");
		if (blogSetting == null) {
			blogSetting = new BlogSetting();
			blogSetting.setCode("theme");
			blogSetting.setName("博客主题");
			blogSetting.setValue("default");
			blogSetting.save();
		}

		request.addModel("current", blogSetting.getValue());

		File folder = new File(AppPaths.WEBINF + "/blog/theme");

		List<String> themes = new ArrayList<>();
		for (File file : folder.listFiles()) {
			if (file.isDirectory()) {
				themes.add(file.getName());
			}
		}
		request.addModel("themes", themes);

		return "success";
	}

	@Path("theme/change")
	@Result(@View(type = ResultType.JSON))
	public String changeTheme(Request request) throws Exception {

		String theme = request.getString("name");
		BlogSetting blogSetting = BlogSetting.load("where code='theme'");

		if (blogSetting == null) {
			blogSetting = new BlogSetting();
			blogSetting.setCode("theme");
			blogSetting.setName("博客主题");
			blogSetting.setValue(theme);
			blogSetting.save();
		} else {
			blogSetting.setValue(theme);
			blogSetting.update();
		}

		// update

		PlatformModule.eventManager.fire("blog.setting:change", SessionFactory.getCurrentDB());

		return "success";
	}

	@Path("theme/copy")
	@Result(@View(type = ResultType.JSON))
	public String copyTheme(Request request) throws IOException {

		String theme = request.getString("name");
		String newname = request.getString("dest");

		FileUtils.copyDirectory(new File(AppPaths.WEBINF + "/blog/theme/" + theme), new File(AppPaths.WEBINF + "/blog/theme/" + newname));

		return "success";
	}

	@Path("theme/delete")
	@Result(@View(type = ResultType.JSON))
	public String deleteTheme(Request request) throws IOException {

		String theme = request.getString("name");
		FileUtils.deleteDirectory(new File(AppPaths.WEBINF + "/blog/theme/" + theme));

		return "success";
	}

	@Path("theme/rename")
	@Result(@View(type = ResultType.JSON))
	public String renameTheme(Request request) throws IOException {

		String theme = request.getString("name");
		String dest = request.getString("dest");

		File file = new File(AppPaths.WEBINF + "/blog/theme/" + theme);
		file.renameTo(new File(AppPaths.WEBINF + "/blog/theme/" + dest));

		return "success";
	}

	@Path("theme/browse")
	@Result(@View(value = "/#{admin}/filemgr/viewfiles", type = ResultType.FORWARD))
	public String browseTheme(Request request) throws IOException {

		String theme = request.getString("theme");
		request.addModel("folder", AppPaths.WEBINF + "/blog/theme/" + theme);

		return "success";
	}

	@Path("theme/choose")
	@Result(@View(value = "/#{admin}/filemgr/filechooser", type = ResultType.FORWARD))
	public String themeFiles(Request request) {

		String theme = BlogUtil.getCurrentTheme();
		request.addModel("folder", AppPaths.WEBINF + "/blog/theme/" + theme);

		return "success";
	}

}
